﻿/*
### LacViet javascript library
* Home          : http://www.lacviet.com.vn
* Code          : site.js
* Date          : 2012-10-09
* Version       : 0.1
* Developer     : Duy Lê 
* Midifier      : LNTANH
* Description   : Common javascript library for all pages
### Licensed by LacViet Computing Coporation
*/

// MultiSelectBox, Kendo Plugin
// -----------------------------------------------------------
(function ($) {

    // shorten references to variables
    var kendo = window.kendo,
        ui = kendo.ui,
        DropDownList = ui.DropDownList,
        keys = kendo.keys,
        SELECT = "select",
        SELECTIONCHANGED = "selectionChanged",
        SELECTED = "k-state-selected",
        HIGHLIGHTED = "k-state-active",
        CHECKBOX = "custom-check-item",
        SELECTALLITEM = "custom-multiselect-selectAll-item",
        MULTISELECTPOPUP = "custom-multiselect-popup",
        EMPTYSELECTION = "custom-multiselect-summary-empty";


    var lineTemplate = '<input type="checkbox" name="#= {1} #" value="#= {0} #" class="' + CHECKBOX + '" />' +
                       '<span data-value="#= {0} #">#= {1} #</span>';



    var MultiSelectBox = DropDownList.extend({

        init: function (element, options) {

            options.template = kendo.template(kendo.format(lineTemplate, options.dataValueField, options.dataTextField));

            // base call to widget initialization
            DropDownList.fn.init.call(this, element, options);
        },

        options: {
            name: "MultiSelectBox",
            index: -1,
            showSelectAll: true,
            preSummaryCount: 1,  // number of items to show before summarising
            emptySelectionLabel: ''  // what to show when no items are selected
        },

        events: [
            SELECTIONCHANGED
        ],

        refresh: function () {

            // base call
            DropDownList.fn.refresh.call(this);

            this._updateSummary();

            $(this.popup.element).addClass(MULTISELECTPOPUP);
        },


        current: function (candidate) {
            return this._current;
        },


        open: function () {
            var that = this;

            this._removeSelectAllItem();

            this._addSelectAllItem();

            if (!that.ul[0].firstChild) {
                that._open = true;

                if (!that._request) {
                    that.dataSource.fetch();
                }
            } else {
                that.popup.open();
                that._scroll(that._current);
            }
        },


        close: function () {

            this._removeSelectAllItem();

            this._current = null;
            this._highlightCurrent();

            this._raiseSelectionChanged();

            DropDownList.fn.close.call(this);
        },

        _raiseSelectionChanged: function () {

            var currentValue = this.value();
            var currentValues = currentValue.length > 0 ? currentValue.split(",") : [];

            if (this._oldValue) {

                var hasChanged = !($(this._oldValue).not(currentValues).length == 0 && $(currentValues).not(this._oldValue).length == 0);

                if (hasChanged) {
                    this.trigger(SELECTIONCHANGED, { newValue: currentValues, oldValue: this._oldValue });
                }
            }
            else if (currentValue.length > 0) {
                this.trigger(SELECTIONCHANGED, { newValue: currentValues, oldValue: this._oldValue });
            }

            this._oldValue = currentValues;
        },


        _addSelectAllItem: function () {

            if (!this.options.showSelectAll) return;

            var firstListItem = this.ul.children('li:first');

            if (firstListItem.length > 0) {
                this.selectAllListItem = $('<li tabindex="-1" role="option" unselectable="on" class="k-item ' + SELECTALLITEM + '"></li>').insertBefore(firstListItem);

                // fake a data object to use for the template binding below
                var selectAllData = {};
                selectAllData[this.options.dataValueField] = '*';
                selectAllData[this.options.dataTextField] = 'All';

                this.selectAllListItem.html(this.options.template(selectAllData));

                this._updateSelectAllItem();

                this._makeUnselectable(); // required for IE8
            }
        },


        _removeSelectAllItem: function () {

            if (this.selectAllListItem) {
                this.selectAllListItem.remove();
            }
            this.selectAllListItem = null;
        },


        _focus: function (li) {
            if (this.popup.visible() && li && this.trigger(SELECT, { item: li })) {
                this.close();
                return;
            }
            this.select(li);
        },


        _highlightCurrent: function () {

            $('li', this.ul).removeClass(HIGHLIGHTED);
            $(this._current).addClass(HIGHLIGHTED);
        },


        _keydown: function (e) {

            // currently ignore Home and End keys
            // can be added later
            if (e.keyCode == kendo.keys.HOME ||
                e.keyCode == kendo.keys.END) {
                e.preventDefault();
                return;
            }

            DropDownList.fn._keydown.call(this, e);
        },


        _move: function (e) {
            var that = this,
                key = e.keyCode,
                ul = that.ul[0],
                down = key === keys.DOWN,
                pressed;


            if (key === keys.UP || down) {

                if (down) {

                    if (!that.popup.visible()) {
                        that.toggle(down);
                    }
                    if (!that._current) {
                        that._current = ul.firstChild;
                    } else {
                        that._current = ($(that._current)[0].nextSibling || that._current);
                    }

                } else {
                    //up

                    // only if anything is highlighted
                    if (that._current) {
                        that._current = ($(that._current)[0].previousSibling || ul.firstChild);
                    }
                }


                if (that._current) {
                    that._scroll(that._current);
                }

                that._highlightCurrent();

                e.preventDefault();
                pressed = true;

            } else {
                pressed = DropDownList.fn._move.call(this, e);
            }

            return pressed;
        },


        selectAll: function () {

            var unselectedItems = this._getUnselectedListItems();
            this._selectItems(unselectedItems);

            // todo: raise custom event
        },

        unselectAll: function () {

            var selectedItems = this._getSelectedListItems();
            this._selectItems(selectedItems);  // will invert the selection

            // todo: raise custom event
        },


        _selectItems: function (listItems) {
            var that = this;

            $.each(listItems, function (i, item) {
                var idx = ui.List.inArray(item, that.ul[0]);
                that.select(idx);  // select OR unselect
            });
        },

        _select: function (li) {
            var that = this,
                 current = that._current,
                 data = that._data(),
                 value,
                 text,
                 idx;

            li = that._get(li);

            if (li && li[0]) {
                idx = ui.List.inArray(li[0], that.ul[0]);
                if (idx > -1) {

                    if (li.hasClass(SELECTED)) {
                        li.removeClass(SELECTED);
                        that._uncheckItem(li);

                        if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
                            this.unselectAll();
                        }
                    } else {
                        li.addClass(SELECTED);
                        that._checkItem(li);

                        if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
                            this.selectAll();
                        }
                    }

                    if (this._open) {
                        that._current(li);
                        that._highlightCurrent();
                    }

                    var selecteditems = this._getSelectedListItems();
                    value = [];
                    text = [];
                    $.each(selecteditems, function (indx, item) {
                        var obj = $(item).children("span").first();
                        value.push(obj.attr("data-value"));
                        text.push(obj.text());
                    });

                    that._updateSummary(text);

                    that._updateSelectAllItem();

                    that._accessor(value, idx);

                    // todo: raise change event (add support for selectedIndex) if required
                }
            }

        },

        _getAllValueListItems: function () {
            if (this.selectAllListItem) {
                return this.ul.children("li").not(this.selectAllListItem[0]);
            } else {
                return this.ul.children("li");
            }
        },

        _getSelectedListItems: function () {
            return this._getAllValueListItems().filter("." + SELECTED);
        },

        _getUnselectedListItems: function () {
            return this._getAllValueListItems().filter(":not(." + SELECTED + ")");
        },

        _getSelectedItemsText: function () {

            var text = [];
            var selecteditems = this._getSelectedListItems();
            $.each(selecteditems, function (indx, item) {
                var obj = $(item).children("span").first();
                text.push(obj.text());
            });
            return text;
        },

        _updateSelectAllItem: function () {

            if (!this.selectAllListItem) return;

            // are all items selected?
            if (this._getAllValueListItems().length == this._getSelectedListItems().length) {
                this._checkItem(this.selectAllListItem);
                this.selectAllListItem.addClass(SELECTED);
            }
            else {
                this._uncheckItem(this.selectAllListItem);
                this.selectAllListItem.removeClass(SELECTED);
            }
        },

        _updateSummary: function (itemsText) {

            if (!itemsText) {
                itemsText = this._getSelectedItemsText();
            }

            if (itemsText.length == 0) {
                this._inputWrapper.addClass(EMPTYSELECTION);
                this.text(this.options.emptySelectionLabel);
                return;
            } else {
                this._inputWrapper.removeClass(EMPTYSELECTION);
            }

            if (itemsText.length <= this.options.preSummaryCount) {
                this.text(itemsText.join(", "));
            }
            else {
                this.text(itemsText.length + ' selected');
            }
        },

        _checkItem: function (itemContainer) {
            if (!itemContainer) return;
            itemContainer.children("input").attr("checked", "checked");
        },

        _uncheckItem: function (itemContainer) {
            if (!itemContainer) return;
            itemContainer.children("input").removeAttr("checked");
        },

        _isItemChecked: function (itemContainer) {
            return itemContainer.children("input:checked").length > 0;
        },

        value: function (value) {
            var that = this,
                idx,
                valuesList = [];

            if (value !== undefined) {

                if (!$.isArray(value)) {
                    valuesList.push(value);
                    this._oldValue = valuesList; // to allow for selectionChanged event
                }
                else {
                    valuesList = value;
                    this._oldValue = value; // to allow for selectionChanged event
                }

                // clear all selections first
                $(that.ul[0]).children("li").removeClass(SELECTED);
                $("input", that.ul[0]).removeAttr("checked");

                $.each(valuesList, function (indx, item) {
                    if (item !== null) {
                        item = item.toString();
                    }

                    that._valueCalled = true;

                    if (item && that._valueOnFetch(item)) {
                        return;
                    }

                    idx = that._index(item);

                    if (idx > -1) {
                        that.select(idx);
                    }

                });

            }
            else {
                return that._accessor();
            }
        }

    });

    ui.plugin(MultiSelectBox);

})(jQuery);




//----------------------------------------------------------------
kendo.culture("vi-VN");

$(window).load(function () {

});


$(document).bind("ajaxComplete", function (event, xmlHttprequest, ajaxOptions) {
    if (xmlHttprequest.status == 200 && xmlHttprequest.responseText == "\"_Logon_\"") {
        if (window.frameElement == null)
            document.location = GetBaseUrl() + "Home/Login";
        else
            window.parent.document.location = GetBaseUrl() + "Home/Login";

        this.location = GetBaseUrl() + "Home/Login";
        return false;
    }
});



function resize() {
    var header = 60, toolbar = 30, statusbar = 25;
    if (document.getElementById("divtoolbar").style.display == "none")
        toolbar = 0;
    if (document.getElementById("divbottom").style.display == "none")
        statusbar = 0;
    if (document.getElementById("divHeader").style.display == "none")
        header = 0;

    var h = $(window).height() - header - toolbar - statusbar;
    var w = $(window).width();
    
    $(".mid").height(h);
    $("#tabstrip").height(h);

    $(".k-treeview").height(h - 30 - 30 * moduleNumber - (moduleNumber));

    var leftPanelWidth = $(".barleft").width();
    $(".barright").width(w - leftPanelWidth - 1 -2);

    var splitter = $("#divMid").data("kendoSplitter");
    // set the size of the pane with ID, pane1
    if(!IsNullOrEmty(splitter))
        splitter.size(".barleft", leftPanelWidth + "px");
}

function HideLeftPanel(interval) {
    if (interval == null)
        interval = 200;

    var leftPanelWidth = $(".barleft").width();
    if (leftPanelWidth > 41) {
        
        $(".barleft").animate({ width: "40px" }, interval, function () {
            $(".headertitle").hide();
            $(".function").hide();
            $(".moduletext").hide();
            resize();
        });
    }
    else {
        $(".barleft").animate({ width: "200px" }, interval, function () {
            $(".headertitle").show();
            $(".function").show();
            $(".moduletext").show(10, function ()
            {
                $(".moduletext").css("display", "inline-block");
            });
            resize();
            
        });
    }
}

function ReloadGridData(gridViewName) {
    var grid = $('#' + gridViewName).data("kendoGrid");;
    grid.dataSource.read();
}

function GetCurrentRowEx(gridView) {
    var selectedRow = gridView.select();

    if (selectedRow != null) {
        var data = gridView.dataItem(selectedRow);

        return data;
    }
    else
        return null;
}

function GetCurrentRow(gridViewName) {

    var gridView = $('#' + gridViewName).data("kendoGrid");

    var selectedRow = gridView.select();

    if (selectedRow != null) {
        var data = gridView.dataItem(selectedRow);
        if(typeof data != "undefined")
            return data;
        return null;
    }
    else
        return null;
}

function ResizeGrid(gridViewName) {
    if (typeof IsModernUI != 'undefined' && IsModernUI == true)
    {
        SetHeightGrid(gridViewName, $(window).height() - $("#top").height() - $(".ApplicationTitle").height()-20);
    }
    else
    {
        SetHeightGrid(gridViewName, $(window).height() - 43);
    }
}

function SetHeightGrid(gridViewName,height)
{
    var gridElement = $("#" + gridViewName);

    gridElement.height(height);

    var dataArea = gridElement.find(".k-grid-content");
    var gridHeight = gridElement.innerHeight();
    var otherElements = gridElement.children().not(".k-grid-content");
    var otherElementsHeight = 0;

    otherElements.each(function () {
        otherElementsHeight += $(this).outerHeight();
    });

    dataArea.height(gridHeight - otherElementsHeight);
}


function FixHeightGrid(gridViewName) {
    var gridElement = $("#" + gridViewName);

    var dataArea = gridElement.find(".k-grid-content");
    var gridHeight = gridElement.innerHeight();
    var otherElements = gridElement.children().not(".k-grid-content");
    var otherElementsHeight = 0;

    otherElements.each(function () {
        otherElementsHeight += $(this).outerHeight();
    });

    dataArea.height(gridHeight - otherElementsHeight);
}


function OpenForm(url, width, height, displayMode, title, modal, name) {

    ShowWindow(url, width, height, displayMode, title, modal, name);
}


function OpenPopup(url, title, w, h) {
    if (w <= 0)
        w = $(window).width() / 2;
    //w = 800;

    if (h <= 0)
        h = $(window).height() / 2;
    //h = 600;

    $(this).popupWindow({
        height: h,
        width: w,
        centerScreen: true,
        menubar: false,
        resizable: true,
        scrollbars: true,
        status: false,
        toolbar: false,
        location: false,
        windowName: title,
        windowURL: url
    });
}

$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },

    getStringVar: function (_string,key) {
        var vars = [], hash;

        var hashes = _string.slice(_string.indexOf('?') + 1).split('&');

        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            if (hash[0] == key) return hash[1];
            
        }
        return "";
    },

    
    ModifiedParaUrl: function (url, key, value) {
        var urlNew, hash;

        urlNew = url.substring(0, url.indexOf('?') + 1);
        var hashes = url.slice(url.indexOf('?') + 1).split('&');

        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            if (i != 0) urlNew = urlNew + "&";
            if (hash[0] == key) {
                urlNew = urlNew + hash[0] + "=" + value;
            }
            else {
                urlNew = urlNew + hash[0] + "=" + hash[1];
            }
            
        }
        return urlNew;
    },

    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    },

    removeParameter: function (url, parameter)
    {
        var fragment = url.split('#');
        var urlparts= fragment[0].split('?');

        if (urlparts.length>=2)
        {
            var urlBase=urlparts.shift(); //get first part, and remove from array
            var queryString=urlparts.join("?"); //join it back up

            var prefix = encodeURIComponent(parameter)+'=';
            var pars = queryString.split(/[&;]/g);
            for (var i= pars.length; i-->0;) {               //reverse iteration as may be destructive
                if (pars[i].lastIndexOf(prefix, 0)!==-1) {   //idiom for string.startsWith
                    pars.splice(i, 1);
                }
            }
            url = urlBase+'?'+pars.join('&');
            if (fragment[1]) {
                url += "#" + fragment[1];
            }
        }
        return url;
    }
});

(function ($) {
    $.fn.serializeDisabled = function () {
        var obj = {};

        $(':disabled[name]', this).each(function () {
            obj[this.name] = $(this).val();
        });
        return $.param(obj);
    }

    $.fn.serializeCustom = function () {
        var obj = {};

        $(':input', this).each(function () {
            if (this.id != "")
                if (this.type == "checkbox")
                    if($(this).attr('checked')=='checked')
                        obj[this.id] = true;
                    else
                        obj[this.id] = false;
                else
                    obj[this.id] = $(this).val();
        });
        return $.param(obj);
    }
})(jQuery);


function PostModel(url, model, callback) {
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(model),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: callback
    });
}

function PostServer(url,dataPost) {
    var data = null;
    var r = null;
    if (IsNullOrEmty(dataPost)) {
        r = $.ajax({
            url: url,
            crossDomain: true,
            dataType: "json",
            async: false,
            cache: false
        });
    }
    else {
        r = $.ajax({
            url: url,
            crossDomain: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: dataPost,
            async: false,
            cache: false
        });
    }

    if (r.responseText == null || r.responseText == "")
        return null;
    try {
        data = $.parseJSON(r.responseText)
    }
    catch (err) {
        data = null;
    }

    
    return data;
}

function ShowControl(name) {
    document.getElementById(name).style.display = "block";
}

function HideControl(name) {
    document.getElementById(name).style.display = "none";
}

function isString(o) {
    return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}

function SelectRowByCondition(gridView, condition) {
    var data = gridView.dataSource.data();

    var i = 0;
    for (i = 0; i < data.length; i++) {
        var dataItem = data[i];
        // use the dataItem
        if (condition(dataItem))
            break;
    }

    SelectRowByIndex(gridView, i);
}

function SelectRowByIndex(gridView, index) {
    var grid = null;
    if (isString(gridView)) {
        grid = $("#" + gridView).data("kendoGrid");
    }
    else {
        grid = gridView;
    }
    var row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(index);
    if (index == -1)
        SelectFirstRow(grid);
    else
        gridView.select(row);
}

function SelectFirstRow(gridView) {
    gridView.select(gridView.tbody.find(">tr:first"));
}

function SelectLastRow(gridView) {
    SelectRowByIndex(gridView, gridView.dataSource.data().length - 1);
}

function ShowBusy(name) {
    $('#' + name).show();
}

function HideBusy(name) {
    $('#' + name).hide();
}

function GetColumnHeader(GridName, ColumnName) {
    var gridview = $('#' + GridName).data("kendoGrid");
    var title = "";
    $(gridview.columns).each(function (i, e) {
        if (e.field == ColumnName) {
            title = $(e.title)[0].innerHTML;
        }
    });
    return title;
}

function menuColumnAction(obj, ObjParent, ParaEx) {
    if (ObjParent != null) {
        if (this.data.alias == "HideCol") {

            $(ObjParent.columns).each(function (i, e) {
                if (obj.id === 'col' + e.field) {
                    ObjParent.hideColumn(i);
                    return;
                }
            });
        }
        else if (this.data.alias == "SavePri" || this.data.alias == "SavePul") {
            var dataGVS = "[";

            $(ObjParent.columns).each(function (i, e) {
                if (i != 0)
                    dataGVS = dataGVS + ",";
                dataGVS = dataGVS + "{";


                dataGVS = dataGVS + "\"GridViewName\":\"" + ObjParent.wrapper[0].id + "\",";
                dataGVS = dataGVS + "\"FormName\":\"" + ParaEx + "\",";
                dataGVS = dataGVS + "\"FieldName\":\"" + e.field + "\",";
                if (typeof e.width == "number")
                    dataGVS = dataGVS + "\"Width\":" + e.width + ",";
                else
                    dataGVS = dataGVS + "\"Width\":" + e.width.replace('px', '') + ",";

                if (e.hidden && e.hidden == true)
                    dataGVS = dataGVS + "\"IsVisible\":" + "false";
                else
                    dataGVS = dataGVS + "\"IsVisible\":" + "true";
                dataGVS = dataGVS + "}";
            });
            dataGVS = dataGVS + "]";
            $.ajax({
                type: "POST",
                url: GetBaseUrl() + "LVGridView/SaveGrid",
                data: dataGVS,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (e) {
                    if (e == true) {
                        var win = ShowMessage('AccNet i', 'SaveCompleted', 'Save Completed.', null, null, 'OK');
                    }
                }
            });
        }

    }
}


function SaveAddRefresh() {
    if (typeof _codeBaseGrid != 'undefined') {
        _codeBaseGrid.SaveAddRefresh();
    }
}

/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function (token, newToken, ignoreCase) {
    var _token;
    var str = this + "";
    var i = -1;

    if (typeof token === "string") {

        if (ignoreCase) {

            _token = token.toLowerCase();

            while ((
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                )) !== -1
            ) {
                str = str.substring(0, i) +
                    newToken +
                    str.substring(i + token.length);
            }

        } else {
            return this.split(token).join(newToken);
        }

    }
    return str;
};

function formatNumber(number, format) {
    if (number == null || number == "")
        number = 0;
    format = format.replaceAll("@", "#");
    return kendo.toString(number, format);
}

function formatData(date, format) {
    if (date == null || date == "")
        return null;
    return kendo.toString(toDate(date), format);
}

function toDate(value) {

    var dateRegExp = /^\/Date\((.*?)\)\/$/;

    var date = dateRegExp.exec(value);

    return new Date(parseInt(date[1]));

}

function ShowMessageErrorLevel1(code, defaultMessage, callback, para1) {
    ShowMessageError(code, defaultMessage, callback, para1);
}

function disableControl(name) {
    if (document.getElementById(name) != null)
        document.getElementById(name).disabled = true;
}

function enableControl(name) {
    if (document.getElementById(name) != null)
        document.getElementById(name).disabled = false;
}

function GetBaseUrl() {
    if (window.frameElement == null)
        return BaseUrl;
    else
        return window.parent.BaseUrl;

}

function attachTextListener(input, func) {
    if (window.addEventListener) {
        input.addEventListener('input', func, false);
    } else
        input.attachEvent('onpropertychange', function () {
            func.call(input);
        });
}

function summarygrid(gridName, field, type, format) {
    var gridview = $('#' + gridName).data("kendoGrid");

    var sum = 0;

    gridview.dataSource.data().forEach(function (e) {
        sum = sum + e[field];
    });

    return formatNumber(sum, format);
}

function CheckComboInList() {
    if (this.value() && this.selectedIndex == -1) {
        if (typeof _codeBaseGrid != "undefined")
            _codeBaseGrid.SetValue($(this)[0].element.context.id, null, true);
        else if (typeof codeBasePopup != "undefined")
            codeBasePopup.SetValue($(this)[0].element.context.id, null, true);

        //var win = ShowMessage('AccNet i', 'ItemInList', 'Do you choose item in list.', SetFocusComboNotInList, null, 'OK');
        $(this).focus();
        //win.ControlAssign = this;
    }

}

function SetFocusComboNotInList(combo) {
    if (this.ControlAssign != null) {
        $(this.ControlAssign).focus();
        this.ControlAssign = null;
    }
}

kendo.ui.DatePicker.prototype.focus = function () {
    var that = this, element = that.element;

    that.dateView.toggle();

    if (element[0] !== document.activeElement) {
        element.focus();
    }
}

kendo.ui.Grid.prototype.urlOld = null;
kendo.ui.Grid.prototype.OldDataSelect = null;
kendo.ui.Grid.prototype.OldRowSelect = null;
kendo.ui.Grid.prototype.IsValidate = false;
kendo.ui.Grid.prototype.IsRowChanged = false;
kendo.ui.Grid.prototype.ReSelect = function () {
    var that = this;
    that.IsReSelect = true;
    that.select(that.OldRowSelect);
}


kendo.ui.Grid.prototype.ColumnIsReadOnly = function (columnName,readOnly)
{
    var that = this;
    var c = null;
    for (var i = 0; i < that.columns.length; i++) {
        if (that.columns[i].field == columnName) {
            c = that.columns[i];
            break;
        }
    }

    if (c == null)
        return true;

    if (typeof readOnly == "undefined")
    {
        return c.editable == "undefined" ? false : !c.editable;
    }
    else
    {
        c.editable = !readOnly;
    }
}

function getLabel(name) {
    return $('#' + name)[0].innerHTML;
}


function setLabel(name, value) {
    $('#' + name)[0].innerHTML = value;
}


function initSearchGrid() {
    if ($(".searchGrid").length != 0) {
        $($(".searchGrid")[0]).keydown(function (e) {
            if (e.keyCode == 13) {
                var gridview = $('#' + this.title).data("kendoGrid");
                var _url = gridview.dataSource.options.transport.read.url;

                if (_url.indexOf("fieldcustomPredicate") < 0) {
                    _url = _url + "&fieldcustomPredicate=&valuecustomPredicate="
                }

                if (_url.indexOf("searchgrid") > 0) {
                    _url = _url.substring(0, _url.indexOf("searchgrid") - 1);
                }
                gridview.dataSource.transport.options.read.url = _url + '&searchgrid=' + encodeURI($(this).val

());
                gridview.dataSource.page(0);
                e.preventDefault();
            }
        })
    }
}

function onSelectMenuFunction(e) {
    if ($(e.item).text().indexOf("More function") == 0) return;
    var a = $(e.item).find($('span'));
    var l = a.length;
    for (i = 0; i < l; i++) {
        if (a[i].id != "") {
            if (a[i].id.indexOf('mnuShowLanguage') == 0)
            {
                ShowLanguage();
            }
            else if (typeof MoreFunctionClick != 'undefined')
                MoreFunctionClick(a[i].id);
        }
    }
}

function ShowLanguage()
{
    var base = GetBaseUrl();
    var url = document.location.href;
    url = url.replace(base, '');
    var i = url.indexOf('/');

    if(i==-1)
        i = url.indexOf('?');

    if (i != -1) {
        url = url.substring(0, i);
    }
    
    url = base + url + '/ShowLanguage';
    ShowWindowCallback(url, 600, 550, "Show Language", function (result) { if (result == 1) document.location.reload(true); }, 1, "");
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function Guid() {
    guid = (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4

()).toLowerCase();
    return guid;
}

function GenarateIDWindow() {
    name = 'w' + (S4() + S4() + S4() + "-4" + S4().substr(0, 3) + S4() + S4() + S4() + S4()).toLowerCase

();
    return name;
}

function ShowWindow(url, width, height, displayMode, title, modal, name) {
    if (window.frameElement == null)
        return _showWindow(url, width, height, displayMode, title, null, modal, name);
    else
        return window.parent._showWindow(url, width, height, displayMode, title, null, modal, name);
}


function ShowWindowCallback(url, width, height, title, callback, modal, name) {
    if (window.frameElement == null)
        return _showWindow(url, width, height, 1, title, callback, modal, name);
    else
        return window.parent._showWindow(url, width, height, 1, title, callback, modal, name);
}

function _showWindow(url, width, height, displayMode, title, callback, modal, name) {
    if (typeof url == "undefined")
        return;
    var urlFull = "";
    if (url.indexOf('http://') < 0) {
        if (url.indexOf('/') == 0) {
            url = url.substring(1, url.length);
        }

        var bt = GetBaseUrl();

        bt = bt.replaceAll("http://", "");
        if (bt.indexOf("/") >= 0) {
            bt = bt.substring(bt.indexOf('/')+1);
        }

        url = url.replace(bt, "");
        
        urlFull = GetBaseUrl() + url;
    }
    else
        urlFull = url;
    if (displayMode == "1") {
        var _win = new WindowPopup();
        _win.id = GenarateIDWindow();
        _win.name = name;
        managewindow.push(_win);

        if (width == 0 || height == 0)
            _win.OpenWindowAuto(urlFull, title, callback, modal);
        else
            _win.OpenWindow(urlFull, title, width, height, callback, modal);
        return _win;
    }
    else {
        document.location = urlFull;
        return null;
    }
}

function ShowMessage(title, code, defaultMessage, callback, para1, button) {
    if (window.frameElement == null)
        return _ShowMessage(title, code, defaultMessage, callback, para1, button);
    else
        return window.parent._ShowMessage(title, code, defaultMessage, callback, para1, button);
}


function ShowMessageError(code, defaultMessage, callback, para1, button) {
    if (window.frameElement == null)
        return _ShowMessage("Error", code, defaultMessage, callback, para1, button);
    else
        return window.parent._ShowMessage("Error", code, defaultMessage, callback, para1, button);
}

function _ShowMessage(title, code, defaultMessage, callback, para1, button) {
    var _win = new WindowPopup();
    _win.id = GenarateIDWindow();

    if (button == null || typeof button == 'undefined' || button == '') {
        button = "OK";
    }

    managewindow.push(_win);
    _win.ShowMessageCode(title, code, defaultMessage, button, callback, para1);
    return _win;
}


function CloseWin(result, id) {
    if (window.frameElement == null)
        _CloseWin(result, id);
    else
        window.parent._CloseWin(result, id);
}

function _CloseWin(result, id) {
    for (i = 0; i < managewindow.length; i++) {
        if (managewindow[i].id == id) {
            managewindow[i].CloseMessage(result);
            RemoveItemArray(managewindow, i);
        }
    }
}

//Goi tu form pupup
function closeWindow(_isRefreshData, key, idWindow) {
    if (window.frameElement == null)
        _closeWindow(_isRefreshData, key, idWindow);
    else
        window.parent._closeWindow(_isRefreshData, key, idWindow);
}

function _closeWindow(_isRefreshData, key, idWindow) {
    for (i = 0; i < managewindow.length; i++) {
        if (managewindow[i].id == idWindow) {
            managewindow[i].CloseMessage({RefreshData :_isRefreshData,Key : key});
            RemoveItemArray(managewindow, i);
        }
    }
}

// Array Remove - By John Resig (MIT Licensed)
function RemoveItemArray(array, from, to) {
    if (from >= array.length) return;
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
}

function GetCurrentModelCombo(comboName) {
    var combobox = $("#" + comboName).data("kendoComboBox");
    if (combobox) {
        var model = combobox.dataSource.data()[combobox.select()];
        return model;
    }
    return null;
}

function GetCurrentModelLVCombo(comboName) {
    var combobox = $("#" + comboName).LVComboBox().data("LVComboBox");
    if (combobox) {
        var model = combobox.CurentModel();
        return model;
    }
    return null;
}

function SetValueForGrid(gridName, field, value) {
    var gridview = $("#" + gridName).data("kendoGrid");

    var item = GetCurrentRowEx(gridview);

    if (typeof item != 'undefined') {
        item.set(field, value);
    }
}

function GetValueForGrid(gridName, field) {
    var gridview = $("#" + gridName).data("kendoGrid");

    var item = GetCurrentRowEx(gridview);

    if (typeof item != 'undefined') {
        if (item[field] != '"[object Object]"')
            return item[field];
    }
    return null;
}

function GetDate(fieldName) {
    var datePicker = $("#" + fieldName + "").data("kendoDatePicker");
    return datePicker.value();
}

function GetDateEx(fieldName) {
    var v = GetDate(fieldName);
    if (!IsNullOrEmty(v))
        return kendo.toString(v, 'dd/MM/yyyy');
    return null;
}


function GetNumber(fieldName) {
    var numerictextbox = $("#" + fieldName + "").data("kendoNumericTextBox");
    // bind to the change event
    return numerictextbox.value();
}

function GetCombobox(fieldName) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    return combobox.value();
}


function GetLVCombobox(fieldName) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    return combobox.value();
}

function SetDate(fieldName, value) {
    var datePicker = $("#" + fieldName + "").data("kendoDatePicker");
    return datePicker.value(value);
}

function SetNumber(fieldName, value) {
    var numerictextbox = $("#" + fieldName + "").data("kendoNumericTextBox");
    // bind to the change event
    return numerictextbox.value(value);
}

function SetCombobox(fieldName, value) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    return combobox.value(value);
}


function SetLVCombobox(fieldName,value,text) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    return combobox.value(value, text);
}

function IsNull(obj)
{
    if (typeof obj == 'undefined' || obj == null)
        return true;
    return false;
}


function IsNullOrEmty(obj) {
    return IsNull(obj) || obj == "";
}

function RepNullOrEmpty(obj,TrueValue,FalseValue) {
    if (IsNullOrEmty(obj))
        return TrueValue;
    else
        if (IsNull(FalseValue))
            return obj;
        else
            return FalseValue;
}


function PrintReport(Module, dataSet, ReportName, Title, storeName, para) {
    var url = GetBaseUrl() + "ReportViewer.aspx?Module=" + Module + "&EntityName=" + dataSet + "&ReportName=" + ReportName + "&FormTitle=" + Title + "&StoreProcedure=" + storeName + '&' + para;

    if (window.frameElement == null)
        window.open(url);
    else
        window.parent.open(url);

};


function PrintReportFromView(Module, dataSet, ReportName, Title, ViewName, para) {
    var url = GetBaseUrl() + "ReportViewer.aspx?Module=" + Module + "&EntityName=" + dataSet + "&ReportName=" + ReportName + "&FormTitle=" + Title + "&ViewName=" + ViewName + '&' + para;

    if (window.frameElement == null)
        window.open(url);
    else
        window.parent.open(url);

};

function SetPredicateForCombo (fieldName, fieldsource, value) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
        combobox.dataSource.filter({ field: fieldsource, operator: "IsEqualTo", value: value });
}

//Predicates
//Ex: [{ "field": "VATGroupID", "operator": "contains","value": "1" }, { "field": "ABC", "operator": "contains", "value": "1" }]
function SetMultiPredicateForCombo(fieldName, Predicates) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    var objfilter = $.parseJSON(Predicates);
    combobox.dataSource.filter(objfilter);
}

//codeBasePopup.SetMultiPredicateComplexForCombo("CashAcctID", "(AccountID.IndexOf(~0)==0||AccountID.IndexOf(~1)==0||AccountID.IndexOf(~2)==0)&&!AccountID.Equals(~3)&&Detail.Equals(~4)", "1|4|5|111|true");
function SetMultiPredicateComplexForCombo(fieldName, Predicates, values) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    combobox.dataSource.filter({ field: Predicates, operator: "IsEqualTo", value: values });

}

//codeBasePopup.SetMultiPredicateComplexForCombo("CashAcctID", "(AccountID.IndexOf(~0)==0||AccountID.IndexOf(~1)==0||AccountID.IndexOf(~2)==0)&&!AccountID.Equals(~3)&&Detail.Equals(~4)", "1|4|5|111|true");
function SetMultiPredicateComplexForLVCombo(fieldName, Predicates, values) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    combobox.filter({ field: Predicates, operator: "IsEqualTo", value: values });
}

function GridLoadData(gridViewName, url)
{
    var grid = $('#' + gridViewName).data("kendoGrid");
    grid.dataSource.transport.options.read.url = url;
    grid.dataSource.read();
}

function GridLoadDataByPredicate(gridViewName, Predicate,Value) {
    var grid = $('#' + gridViewName).data("kendoGrid");

    Predicate = Predicate.replaceAll("=", "_equals_");
    Predicate = Predicate.replaceAll("&&", "_and_");
    Predicate = encodeURI(Predicate);
    Value = encodeURI(Value);

    var url = $.ModifiedParaUrl(grid.dataSource.transport.options.read.url, "fieldcustomPredicate", Predicate);
    url = $.ModifiedParaUrl(url, "valuecustomPredicate", Value);

    grid.dataSource.transport.options.read.url = url;
    grid.dataSource.read();
}


//trên lưới con khi khi dùng tab edit thì không chọn được dòng
function FixGridTabEdit(o)
{
    setTimeout(function () {
        if (!IsNull(o) && !IsNull(o.current()))
            o.select(o.current().parent());
    }, 10);
    
}

kendo.data.DataSource.prototype.AutoLoadData = true;

function RequestStart(e)
{
    if (e.sender.AutoLoadData == false) {
        e.preventDefault();
    }
}

function CheckPermission(type)
{
    if (permission.length == 0) return false;
    for (var i = 0; i < permission.length; i++) {
        if (permission[i].FType == type)
            return permission[i].FIsActive;
    }
    return false;
}


function updateCell(gridViewName, columnName, rowIndex, model)
{
    setTimeout(function () {
        var gridview = $("#" + gridViewName).data("kendoGrid");
        var colIndex = -1;

        var col = null;
        for (var i = 0; i < gridview.columns.length; i++) {
            if (gridview.columns[i].field == columnName) {

                colIndex = i;
                col = gridview.columns[i];
                break;
            }
        }

        if (colIndex == -1) return;
        if (gridview.tbody.children().length < rowIndex) return;

        var row = gridview.tbody.children()[rowIndex];
        var cell = $(row).children()[colIndex];

        if (!cell) return;

        gridview._displayCell($(cell), col, model);
    }, 50);
}

function closeCell(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    gridview.closeCell();
}

function editCell(gridViewName, columnName, next, rowIndex, modelselect) {
    setTimeout(function () {
        var gridview = $("#" + gridViewName).data("kendoGrid");
        var colIndex = -1;
        var col = null;
        for (var i = 0; i < gridview.columns.length; i++) {
            if (gridview.columns[i].field == columnName) {
                if (next)
                {
                    for (var j = i+1; j < gridview.columns.length; j++) {
                        if (gridview.columns[j].hidden!=true) {
                            colIndex = j;
                            col = gridview.columns[j];
                            break;
                        }
                    }
                }

                colIndex = i;

                col = gridview.columns[i];
                break;
            }
        }

        if (colIndex == -1) return;

        if (typeof rowIndex == "undefined" || rowIndex == null)
        {
            if (modelselect)
            {
                rowIndex = gridview.dataSource.data().indexOf(modelselect);
            }
            else
            {
                var model = GetCurrentRowEx(gridview);
                if (model)
                    rowIndex = gridview.dataSource.data().indexOf(model);
            }
            
        }

        if (typeof rowIndex == "undefined" || gridview.tbody.children().length < rowIndex) return;

        var row = gridview.tbody.children()[rowIndex];
        var cell = $(row).children()[colIndex];

        if (!cell) return;

        SelectRowByIndex(gridview, rowIndex);
        gridview.closeCell();
        gridview.editCell($(cell));
    }, 50);
}

function SetAgainGridFocus(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    var current = gridview.current();
    if (current.length > 0) {
        var inp = current.find(".k-input");
        for (var i = 0; i < inp.length; i++) {
            if ($(inp).is(':visible')) {
                $(inp).focus();
            }
        }
    }
}

function RowCurrentIndex(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    var current = GetCurrentRowEx(gridview);
    if (current)
    {
        return gridview.dataSource.data().indexOf(current);
    }
    else
    {
        return -1;
    }
}

var BridgeFunction = null;

function SetBridgeFunction(f)
{
    if (window.frameElement == null)
        BridgeFunction = f;
    else
        window.parent.BridgeFunction = f;
}

function CallBridgeFunction() {
    if (window.frameElement == null)
        return BridgeFunction();
    else
        return window.parent.BridgeFunction();
}

function LinkAdd(name, functionID,fieldvalue)
{
    var data = PostServer(GetBaseUrl() + 'Shared/GetFunction?functionID=' + functionID);
    if (!IsNull(data))
    {
        var value= GetCombobox(name);
        var url = GetBaseUrl() + data.Url + "/Add";
        if (data.Width == 0)
        {
            ShowWindowCallback(url, 0, 0, 'Add ' + data.CustomName, function () { LinkRefresh(name, functionID, fieldvalue); });
        }
        else
        {
            ShowWindowCallback(url, data.Width, data.Height, 'Add ' + data.CustomName, function () { LinkRefresh(name, functionID, fieldvalue); });
        }
    }
}

function LinkRefresh(name, functionID, fieldvalue) {
    if ($("#" + name).length > 0)
    {
        var combobox = $("#" + name + "").data("kendoComboBox");
        combobox.dataSource.read();
        combobox.refresh();
    }
}


function LVLinkAdd(name, functionID, fieldvalue) {
    var data = PostServer(GetBaseUrl() + 'Shared/GetFunction?functionID=' + functionID);
    if (!IsNull(data)) {
        var url = GetBaseUrl() + data.Url + "/Add";
        if (data.Width == 0) {
            ShowWindowCallback(url, 0, 0, 'Add ' + data.CustomName, function () { LVLinkRefresh(name, functionID, fieldvalue); });
        }
        else {
            ShowWindowCallback(url, data.Width, data.Height, 'Add ' + data.CustomName, function () { LVLinkRefresh(name, functionID, fieldvalue); });
        }
    }
}

function LVLinkRefresh(name, functionID, fieldvalue) {
    if ($("#" + name).length > 0) {
        var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
        combobox.ReadData(0);
    }
}

function HideToolbarWindowOfMetro(hide)
{
    if ($("#windowsopen").length > 0) {
        if(hide)
            $("#windowsopen").hide();
        else
            $("#windowsopen").show();
    }

    if ($("#navbar").length > 0) {
        if (hide)
            $("#navbar").hide();
        else
            $("#navbar").show();
    }
}

function EnableMenu(menuName,menuItem,enable) {
    var menu = $("#" + menuName).data("kendoMenu");
    menu.enable($("#" + menuItem).parent().parent(), enable);
}

function RefreshExcel(src)
{
    src = $.getStringVar(src, "src");
    return PostServer(GetBaseUrl() + 'Shared/RefreshExcel?src=' + src);
}

function ChooseColor(gridName, FieldName)
{
    
    if(PreShowColorChoose != 'undefined')
        if(PreShowColorChoose() == false)  return;

    if ($("#ChooseColorDiv").length == 0) {
        $("<div id='ChooseColorDiv' style='position: absolute;top:50%;left:0px;width:100%;height:0px;overflow: visible;background:red;'><div style='width:252px;height:240px;margin-left:-125px;position:absolute;top:-100px;left:50%;background:#ccc;'><div id='ColorPi'/><button type='Button' onclick='applyChooseColor(\"" + gridName + "\",\"" + FieldName + "\")'>Choose</button><button type='Button' onclick='closeChooseColor()'>Close</button></div></div>").appendTo("body");


        $("#ColorPi").kendoFlatColorPicker({
            preview: false,
            value: "#000",

        });
    }
    else {
        $("#ChooseColorDiv").show();
    }
    
}

function closeChooseColor()
{
    $("#ChooseColorDiv").hide();
}


function applyChooseColor(gridName, FieldName) {

    var data = GetCurrentRow(gridName);
    var p = $("#ColorPi").data("kendoFlatColorPicker");
    if (data != null) {
        data.set(FieldName, p.value());
    }

    $("#ChooseColorDiv").hide();
}